package engine.query;

import static storage.sql.Types.INTEGER;

import java.util.Collection;
import java.util.List;

import compiler.absyn.Constant;
import compiler.absyn.IntConstant;
import compiler.absyn.StringConstant;

import storage.record.RID;
import storage.record.RecordFile;
import storage.record.Schema;
import storage.record.TableInfo;
import storage.tx.Transaction;

public class TableScan implements UpdateScan {
	private RecordFile rf;
	private Schema sch;


	public TableScan(TableInfo ti, Transaction tx) {
		rf  = new RecordFile(ti, tx);
		sch = ti.schema();
	}

	// Scan methods

	public void beforeFirst() {
		rf.beforeFirst();
	}

	public boolean next() {
		return rf.next();
	}

	public void close() {
		rf.close();
	}


	public Constant getVal(String fldname) {
		if (sch.type(fldname) == INTEGER)
			return new IntConstant(rf.getInt(fldname));
		else
			return new StringConstant(rf.getString(fldname));
	}

	public int getInt(String fldname) {
		return rf.getInt(fldname);
	}

	public String getString(String fldname) {
		return rf.getString(fldname);
	}

	public boolean hasField(String fldname) {
		return sch.hasField(fldname);
	}

	// UpdateScan methods

	
	public void setVal(String fldname, Constant val) {
		if (sch.type(fldname) == INTEGER)
			rf.setInt(fldname, (Integer)val.asJavaVal());
		else
			rf.setString(fldname, (String)val.asJavaVal());
	}

	public void setInt(String fldname, int val) {
		rf.setInt(fldname, val);
	}

	public void setString(String fldname, String val) {
		rf.setString(fldname, val);
	}

	public void delete() {
		rf.delete();
	}

	public void insert() {
		rf.insert();
	}

    public RID getRid() {
		return rf.currentRid();
	}

    public void moveToRid(RID rid) {
		rf.moveToRid(rid);
	}
    
    public Collection<String> getFieldSet(){
    	return sch.fields();
    }
    public List<String> getKeyFieldSet(){
    	return sch.getKeyset();
    }
    public List<String> getNotNullFieldSet(){
    	return sch.getNotNullset();
    }
    public List<String> getFKeyset(){
    	return sch.getFKeyset();
    }
    public List<String> getCheckset(){
    	return sch.getCheckset();
    }
    public List<String> getRefset(){
    	return sch.getRefset();
    }
//    public boolean isfkey(String fldname){
//    	return sch.isfkey(fldname);
//    }
    public String fkeytblname(String fldname){
    	return sch.fkeytblname(fldname);
    }
    public String fkeyfldname(String fldname){
    	return sch.fkeyfldname(fldname);
    }
    public String rkeytblname(String fldname){
    	return sch.rktblname(fldname);
    }
    public String rkeyfldname(String fldname){
    	return sch.rkfldname(fldname);
    }
    public String termstring(String fldname){
    	return sch.termstring(fldname);
    }
    public int ischeck(String fldname){
    	return sch.ischeck(fldname);
    }
}
